<?php

namespace app\admin\logic;

use app\common\model\mysql\GroupModel;
use app\common\model\mysql\RuleModel;
use app\common\logic\BaseLogic;

class GroupLogic extends BaseLogic
{
    public function index($request)
    {
        $group = GroupModel::field('id,name,parent_id,status')->order(['id' => 'ASC'])->select()->each(function ($item) {
            $item->system_name = !empty($item->system->name) ? $item->system->name : '';
        });
        if (!empty($group[0])) {
            $group = getTree($group->toArray());
            $list = arrayToObj(structureTree($group));
        }
        return view('Group/group', compact('list'));
    }

    public function create($request)
    {
        // 获取上级组数据
        $groupList = GroupModel::getList(['status' => 1], ['id', 'name', 'parent_id', 'status'], [], ['id' => 'ASC']);
        if (!empty($groupList[0])) {
            $groupList = getTree($groupList->toArray());
            $list = arrayToObj(structureTree($groupList));
        }

        $ruleHtml = $this->getRule(1);
        return view('Group/group_add', compact('list', 'ruleHtml'));
    }

    public function save($request)
    {
        $param = $request->param();
        $inputData = [
            'name' => $param['name'],
            'parent_id' => $param['parent_id'],
            'rules' => $param['rule_ids'] ?: '*',
            'status' => $param['status'],
        ];
        try {
            GroupModel::addData($inputData);
        } catch (\Exception $e) {
            return $this->responseError('保存失败');
        }
        return $this->responseSuccess('保存成功');
    }

    public function edit($request, $id)
    {
        // 获取上级组数据
        $where[] = ['id', '<>', $id];
        $where[] = ['status', '=', 1];
        $group_list = GroupModel::getList($where, ['id', 'name', 'parent_id', 'status'], [], ['id' => 'ASC']);
        if (!empty($group_list[0])) {
            $group_list = getTree(objToArray($group_list));
            $list = arrayToObj(structureTree($group_list));
        }
        $info = GroupModel::getOne(['id' => $id]);
        $rule_html = $this->getRule($info->parent_id, $id);
        return view('Group/group_edit', compact('info', 'list', 'rule_html'));
    }

    public function update($request, $id)
    {
        $param = $request->param();
        $inputData = [
            'name' => $param['name'],
            'parent_id' => $param['parent_id'],
            'rules' => $param['rule_ids'] ?: '*',
            'status' => $param['status']
        ];


        try {
            GroupModel::editData($inputData, ['id' => $id]);
        } catch (\Exception $e) {
            return $this->responseError('保存失败');
        }
        return $this->responseSuccess('保存成功');
    }

    protected function getRule($parentId, $group_id = '')
    {
        $ruleHtml = '';

        $group = GroupModel::getOne(['id' => $parentId, 'status' => '1']);

        if (!empty($group->rules)) {
            if ($group->rules == '*') {
                $ruleList = RuleModel::getList(['status' => '1'], ['id', 'name', 'route', 'parent_id', 'icon', 'is_menu'], [], ['sort' => 'ASC']);
            } else {
                $rules = explode(',', $group->rules);
                $where[] = ['id', 'in', $rules];
                $where[] = ['status', '=', '1'];
                $ruleList = RuleModel::getList($where, ['id', 'name', 'route', 'parent_id', 'icon', 'is_menu'], [], ['sort' => 'ASC']);
            }
            $ruleList = getTree(objToArray($ruleList));

            // 获取组信息
            if (!empty($group_id)) {
                $rulesIds = GroupModel::getAlone(['id' => $group_id], 'rules');
                $rulesIds = explode(',', $rulesIds);
            } else {
                $rulesIds = [];
            }
            $ruleHtml = $this->getRuleHtml($ruleList, $rulesIds);
        }
        return $ruleHtml;
    }


    protected function getRuleHtml($rule_list, $rule_ids = [])
    {
        $rule_html = "<ul>";

        // 编辑菜单属性
        foreach ($rule_list as $key => $rule) {

            $selected = "";
            if (!empty($rule_ids)) {
                if (in_array($rule["id"], $rule_ids)) {
                    $selected = "data-jstree='{\"selected\" :true}'";
                }
            } else {
                $selected = "data-jstree='{\"selected\" :true}'";
            }

            // 判断是否存在子菜单,存在就添加 子菜单的 类名
            if (!empty($rule['sub_item'])) {
                if ($rule['sub_item'][0]['is_menu'] == 1) {
                    $rule_html .= "<li class='item-node' data-id='{$rule["id"]}'>{$rule["name"]}";
                } else {
                    $rule_html .= "<li class='item-auth-node item-node' data-id='{$rule["id"]}'>{$rule["name"]}";
                }

                // 回调子菜单
                $rule_html .= self::getRuleHtml($rule['sub_item'], $rule_ids);

                $rule_html .= "</li>";
            } else {

                if ($rule["is_menu"] == 1) {
                    $rule_html .= "<li class='item-node' data-id='{$rule["id"]}' {$selected} >{$rule["name"]}</li>";
                } else {
                    $rule_html .= "<li data-id='{$rule["id"]}' {$selected}>{$rule["name"]}</li>";
                }
            }
            $rule_html .= "</li>";
        }
        $rule_html .= "</ul>";
        return $rule_html;
    }
}